import { _decorator, Camera, Component, EventTouch, input, Input, Node, PhysicsSystem } from 'cc';
import { Aircraft } from './Aircraft';
import { GGResource } from '../../../framework/core/base/GGResource';
import { Prefab } from 'cc';
import { instantiate } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GameCtrl')
export class GameCtrl extends Component {
    @property({ type: Camera, displayName: "摄像头" })
    camera: Camera;
    
    start() {
        this.initListener()
        this.initLevel()
    }
    
    protected onDestroy(): void {
        input.off(Input.EventType.TOUCH_START)
        input.off(Input.EventType.TOUCH_MOVE)
        input.off(Input.EventType.TOUCH_END)
    }

    // ------------------- 初始化 ------------------- //
    private initListener() {
        input.on (Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.on (Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on (Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    private initLevel() {
        GGResource.load("game:res/prefabs/关卡", Prefab).then((pre: Prefab) => {
            const levelNode = instantiate(pre)
            levelNode.parent = this.node
        });
    }

    // ------------------- 事件 ------------------- //
    private onTouchStart(event: EventTouch) {
        
    }

    onTouchMove(event: EventTouch) {
        
    }

    // 触摸屏幕，目标为选中的 3D 对象
    private onTouchEnd(e: EventTouch): void {
        let pos = e.getLocation();
        let ray = this.camera.screenPointToRay(pos.x, pos.y);
        
        // 如果选中了节点
        if (PhysicsSystem.instance.raycastClosest(ray) == true) {
            // 获取射线最短的检测结果
            var checkNode = PhysicsSystem.instance.raycastClosestResult.collider.node;
            var aircraftCom = checkNode.getComponent(Aircraft)

            if (aircraftCom) {
                aircraftCom.aircraftSetUp()
            }
        }
    }
}


